import sys
import os
from PyQt6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QPushButton, 
                            QLabel, QFileDialog, QProgressBar, QFrame, QSizePolicy)
from PyQt6.QtCore import Qt, QThread, pyqtSignal, QSize
from PyQt6.QtGui import QDragEnterEvent, QDropEvent, QFont
from video_processor import VideoProcessor

class VideoLoadWorker(QThread):
    """视频加载工作线程"""
    progress = pyqtSignal(int)
    finished = pyqtSignal(bool, str)
    info_ready = pyqtSignal(dict)

    def __init__(self, video_path: str):
        super().__init__()
        self.video_path = video_path
        self.processor = VideoProcessor()

    def run(self):
        try:
            # 加载视频
            success = self.processor.load_video(self.video_path)
            if success:
                # 获取视频信息
                info = self.processor.get_video_info()
                self.info_ready.emit(info)
                self.finished.emit(True, "视频加载成功")
            else:
                self.finished.emit(False, "视频加载失败")
        except Exception as e:
            self.finished.emit(False, f"加载出错: {str(e)}")
        finally:
            self.processor.release()

class VideoLoaderView(QWidget):
    """视频加载与信息展示视图"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.video_path = None
        self.processor = VideoProcessor()
        self.init_ui()

    def init_ui(self):
        """初始化UI"""
        # 设置窗口属性
        self.setAcceptDrops(True)
        self.setMinimumSize(800, 600)

        # 创建主布局
        main_layout = QVBoxLayout(self)
        main_layout.setSpacing(20)
        main_layout.setContentsMargins(20, 20, 20, 20)

        # 文件选择区域
        file_frame = QFrame()
        file_frame.setFrameStyle(QFrame.Shape.StyledPanel)
        file_layout = QHBoxLayout(file_frame)
        
        self.file_label = QLabel("未选择文件")
        self.file_label.setStyleSheet("""
            QLabel {
                padding: 10px;
                background: #f0f0f0;
                border-radius: 5px;
                font-size: 14px;
            }
        """)
        
        select_btn = QPushButton("选择视频")
        select_btn.setStyleSheet("""
            QPushButton {
                padding: 10px 20px;
                background: #2196F3;
                color: white;
                border: none;
                border-radius: 5px;
                font-size: 14px;
            }
            QPushButton:hover {
                background: #1976D2;
            }
        """)
        select_btn.clicked.connect(self.select_video)
        
        file_layout.addWidget(self.file_label, 1)
        file_layout.addWidget(select_btn)
        main_layout.addWidget(file_frame)

        # 视频信息展示区域
        self.info_frame = QFrame()
        self.info_frame.setFrameStyle(QFrame.Shape.StyledPanel)
        self.info_frame.setStyleSheet("""
            QFrame {
                background: white;
                border-radius: 10px;
                padding: 20px;
            }
        """)
        info_layout = QVBoxLayout(self.info_frame)
        
        # 信息标签
        self.info_labels = {}
        info_items = [
            ("duration", "视频时长"),
            ("fps", "帧率(FPS)"),
            ("total_frames", "总帧数"),
            ("width", "宽度"),
            ("height", "高度"),
            ("path", "文件路径")
        ]
        
        for key, text in info_items:
            label = QLabel(f"{text}: --")
            label.setStyleSheet("""
                QLabel {
                    font-size: 14px;
                    padding: 5px;
                }
            """)
            self.info_labels[key] = label
            info_layout.addWidget(label)
        
        info_layout.addStretch()
        main_layout.addWidget(self.info_frame)

        # 进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.setStyleSheet("""
            QProgressBar {
                border: 2px solid #f0f0f0;
                border-radius: 5px;
                text-align: center;
                height: 25px;
            }
            QProgressBar::chunk {
                background: #2196F3;
                border-radius: 3px;
            }
        """)
        self.progress_bar.hide()
        main_layout.addWidget(self.progress_bar)

        # 操作按钮区域
        btn_layout = QHBoxLayout()
        
        self.load_btn = QPushButton("加载视频")
        self.load_btn.setStyleSheet("""
            QPushButton {
                padding: 10px 20px;
                background: #4CAF50;
                color: white;
                border: none;
                border-radius: 5px;
                font-size: 14px;
            }
            QPushButton:hover {
                background: #388E3C;
            }
            QPushButton:disabled {
                background: #BDBDBD;
            }
        """)
        self.load_btn.clicked.connect(self.load_video)
        self.load_btn.setEnabled(False)
        
        self.clear_btn = QPushButton("清除")
        self.clear_btn.setStyleSheet("""
            QPushButton {
                padding: 10px 20px;
                background: #F44336;
                color: white;
                border: none;
                border-radius: 5px;
                font-size: 14px;
            }
            QPushButton:hover {
                background: #D32F2F;
            }
        """)
        self.clear_btn.clicked.connect(self.clear_video)
        
        btn_layout.addWidget(self.load_btn)
        btn_layout.addWidget(self.clear_btn)
        main_layout.addLayout(btn_layout)

    def select_video(self):
        """选择视频文件"""
        file_path, _ = QFileDialog.getOpenFileName(
            self,
            "选择视频文件",
            "",
            "视频文件 (*.mp4 *.avi *.mkv *.mov);;所有文件 (*.*)"
        )
        if file_path:
            self.video_path = file_path
            self.file_label.setText(os.path.basename(file_path))
            self.load_btn.setEnabled(True)

    def load_video(self):
        """加载视频"""
        if not self.video_path:
            return

        # 禁用按钮
        self.load_btn.setEnabled(False)
        self.clear_btn.setEnabled(False)
        
        # 显示进度条
        self.progress_bar.setValue(0)
        self.progress_bar.show()
        
        # 创建工作线程
        self.worker = VideoLoadWorker(self.video_path)
        self.worker.progress.connect(self.update_progress)
        self.worker.finished.connect(self.load_finished)
        self.worker.info_ready.connect(self.update_info)
        self.worker.start()

    def update_progress(self, value):
        """更新进度条"""
        self.progress_bar.setValue(value)

    def load_finished(self, success: bool, message: str):
        """加载完成处理"""
        self.progress_bar.hide()
        self.load_btn.setEnabled(True)
        self.clear_btn.setEnabled(True)
        
        if not success:
            self.file_label.setText(f"加载失败: {message}")

    def update_info(self, info: dict):
        """更新视频信息"""
        # 格式化时长
        duration = info.get("duration", 0)
        minutes = int(duration // 60)
        seconds = int(duration % 60)
        duration_str = f"{minutes:02d}:{seconds:02d}"
        
        # 更新标签
        self.info_labels["duration"].setText(f"视频时长: {duration_str}")
        self.info_labels["fps"].setText(f"帧率(FPS): {info.get('fps', 0):.2f}")
        self.info_labels["total_frames"].setText(f"总帧数: {info.get('total_frames', 0)}")
        self.info_labels["width"].setText(f"宽度: {info.get('width', 0)}")
        self.info_labels["height"].setText(f"高度: {info.get('height', 0)}")
        self.info_labels["path"].setText(f"文件路径: {info.get('path', '')}")

    def clear_video(self):
        """清除当前视频"""
        self.video_path = None
        self.file_label.setText("未选择文件")
        self.load_btn.setEnabled(False)
        
        # 清除信息显示
        for label in self.info_labels.values():
            label.setText(label.text().split(":")[0] + ": --")

    def dragEnterEvent(self, event: QDragEnterEvent):
        """拖拽进入事件"""
        if event.mimeData().hasUrls():
            event.acceptProposedAction()

    def dropEvent(self, event: QDropEvent):
        """拖拽释放事件"""
        files = event.mimeData().urls()
        if files:
            file_path = files[0].toLocalFile()
            if file_path.lower().endswith(('.mp4', '.avi', '.mkv', '.mov')):
                self.video_path = file_path
                self.file_label.setText(os.path.basename(file_path))
                self.load_btn.setEnabled(True) 